﻿using FreeOPC.Config;
using FreeOPC.Config.Model;
using FreeOPC.Server.MQTTService;
using FreeOPC.Server.OPCServer;
using FreeOPC.Server.sqlite;
using FreeOPC.Server.Window;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace FreeOPC.Server.Host
{
    public class HttpOPCController : Controller
    {
        [HttpGet]
        public async Task<string> Test(string id, string msg)
        {
            var _mqttService = ServiceLocator.instance.GetRequiredService<MqttService>();

            _mqttService.TestPublish(id, msg);
            return "OK";
        }




        /// <summary>
        /// 插入到OPC
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<string> InsertOPC([FromBody] OPCServerDTO model)
        {
            if (SqliteHelper.InsertOPC(model.DAProgId, model.AEProgId, model.OPCServerIP, model.SubsystemTypeId))
            {
                return "OK";
            }
            else
            {
                return "NOK";
            }
        }

        /// <returns></returns>
        [HttpPost]
        public async Task<OPCServerModel> SearchOPC([FromBody] OPCServerDTO model)
        {

            var opcServerList = SqliteHelper.GetDataTable("select * from opcserver where OPCServerIP='" + model.OPCServerIP + "'");
            if (opcServerList.Rows.Count > 0)
            {
                var opcServer = opcServerList.Rows[0];
                var svrMode = new OPCServerModel()
                {
                    DAProgId = opcServer["DAProgId"].ToString(),
                    AEProgId = opcServer["AEProgId"].ToString(),
                    Id = int.Parse(opcServer["Id"].ToString()),
                    OPCServerIP = opcServer["OPCServerIP"].ToString(),
                    SubsystemTypeId = int.Parse(opcServer["SubsystemTypeId"].ToString())
                };
                return svrMode;
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 删除OPC
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<string> DeleteOPC([FromBody] OPCServerModel model)
        {
            if (SqliteHelper.DeleteOPC(model.OPCServerIP))
            {
                return "OK";
            }
            else
            {
                return "NOK";
            }
        }

        /// <summary>
        /// 删除OPC
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<string> DeleteALLOPC()
        {
            if (SqliteHelper.DeleteALLOPC())
            {
                return "OK";
            }
            else
            {
                return "NOK";
            }
        }

        /// <summary>
        /// 此处需要重启OPC SERVER
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<string> UpdateOPC([FromBody] OPCServerModel model)
        {
            if (SqliteHelper.DeleteOPC(model.OPCServerIP))
            {
                SqliteHelper.InsertOPC(model.DAProgId, model.AEProgId, model.OPCServerIP, model.SubsystemTypeId);
                return "OK";
            }
            else
            {
                return "NOK";
            }
        }


        /// <summary>
        /// 需要添加TagItem
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<string> UpdateTagItem([FromBody] ItemName model)
        {
            if (SqliteHelper.DeleteItem(model.Name, model.OPCIP, model.GroupName))
            {
                SqliteHelper.InsertItem(model.OPCIP, model.Name, model.GroupName);
                return "OK";
            }
            else
            {
                return "NOK";
            }
        }

        /// <summary>
        /// 将ITEM 插入到Group中
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<string> InsertItem([FromBody] ItemName model)
        {
            if (SqliteHelper.InsertItem(model.OPCIP, model.Name, model.GroupName))
            {
                var opcServer = OPCStartService._daServerList.Where(x => x._serverConfig.OPCServerIP == model.OPCIP).FirstOrDefault();
                if (opcServer != null)
                {
                    var result = opcServer.AddItem(model.Name, model.GroupName);

                    if (result)
                    {
                        SerilogServer.WriteLog("InsertItem", new string[] { model.Name + "添加订阅成功 GroupName=" + model.GroupName });
                    }
                    else
                    {
                        SerilogServer.WriteLog("InsertItem", new string[] { model.Name + "已经添加订阅成功 GroupName=" + model.GroupName });
                        return "NOK";
                    }
                }
                else
                {
                    SerilogServer.WriteLog("InsertItem", new string[] { model.OPCIP + "OPC不存在" });
                }
                return "OK";
            }
            else
            {
                return "NOK";
            }
        }


        /// <summary>
        /// 测试TAG
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<string> InsertItemTEST([FromBody] ItemName model)
        {
            for (int i = 1; i < 10; i++)
            {
                List<string> tagItems = new List<string>();
                tagItems.Add("PVTEST" + i.ToString().PadLeft(4, '0') + ".PV");
                tagItems.Add("PVTEST" + i.ToString().PadLeft(4, '0') + ".HH");
                tagItems.Add("PVTEST" + i.ToString().PadLeft(4, '0') + ".PH");
                tagItems.Add("PVTEST" + i.ToString().PadLeft(4, '0') + ".PL");
                tagItems.Add("PVTEST" + i.ToString().PadLeft(4, '0') + ".LL");
                //HH,HI,LO,LL,VL,DL
                foreach (var tagitem in tagItems)
                {
                    model.GroupName = "Area1";
                    if (SqliteHelper.InsertItem(model.OPCIP, tagitem, model.GroupName))
                    {
                        //var opcServer = OPCStartService._daServerList.Where(x => x._serverConfig.OPCServerIP == model.OPCIP).FirstOrDefault();
                        //if (opcServer != null)
                        //{
                        //    opcServer.AddItem(tagitem, model.GroupName);
                        //}
                        //else
                        //{
                        //    SerilogServer.WriteLog("InsertItemTEST", new string[] { model.OPCIP + "OPC不存在" });
                        //}

                    }
                    else
                    {

                    }
                }
            }
            return "OK";
        }

        /// <summary>
        /// 增加订阅
        /// </summary>
        /// <param name="GroupModel"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<string> RegisterServerSubScript([FromBody] SubscriptionModel GroupModel)
        {
            var opcServer = OPCStartService._daServerList.Where(x => x._serverConfig.OPCServerIP == GroupModel.OPCIP).FirstOrDefault();
            if (opcServer != null)
            {
                opcServer.RegisterServerSubScript(GroupModel.GroupName);
            }
            else
            {
                SerilogServer.WriteLog("RegisterServerSubScript", new string[] { GroupModel.OPCIP + "OPC不存在" });
            }
            return "OK";
        }

        /// <summary>
        /// 增加订阅
        /// </summary>
        /// <param name="GroupModel"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<string> RemoveServerSubScript([FromBody] SubscriptionModel GroupModel)
        {
            var opcServer = OPCStartService._daServerList.Where(x => x._serverConfig.OPCServerIP == GroupModel.OPCIP).FirstOrDefault();
            if (opcServer != null)
            {
                opcServer.RemoveServerSubScript(GroupModel.GroupName);
            }
            else
            {
                SerilogServer.WriteLog("RemoveServerSubScript", new string[] { GroupModel.OPCIP + "OPC不存在" });
            }
            return "OK";
        }


        /// <summary>
        /// 删除Item 删除sqlite的同时去掉订阅
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<string> DeleteItem([FromBody] ItemName model)
        {
            if (SqliteHelper.DeleteItem(model.Name, model.OPCIP, model.GroupName))
            {
                var opcServer = OPCStartService._daServerList.Where(x => x._serverConfig.OPCServerIP == model.OPCIP).FirstOrDefault();
                if (opcServer != null)
                {
                    Console.WriteLine(model.Name + "开始移除成功");
                    opcServer.RemoveItem(model.Name, model.GroupName);
                }
                else
                {
                    SerilogServer.WriteLog("DeleteItem", new string[] { model.OPCIP + model.Name + "OPC不存在" });
                }
                return "OK";
            }
            else
            {
                SerilogServer.WriteLog("DeleteItem", new string[] { model.OPCIP + model.Name + "已经被删除" });
                return "OK";
            }
        }

        /// <summary>
        /// 删除全部ITEM sqllite
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<string> DeleteAllItem()
        {
            if (SqliteHelper.DeleteALLItem())
            {
                return "OK";
            }
            else
            {
                return "NOK";
            }
        }

        /// <summary>
        /// 获取所有的Station
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<List<string>> GetAllStations([FromBody] StationRequestModel model)
        {
            var opcServer = OPCStartService._daServerList.Where(x => x._serverConfig.OPCServerIP == model.OPCIP).FirstOrDefault();
            if (opcServer != null)
            {
                return opcServer.GetAllStations().Select(o => o.StationName).ToList();
            }
            else
            {
                SerilogServer.WriteLog("GetAllStations", new string[] { model.OPCIP + "OPC不存在" });
            }
            return new List<string>();
        }


        /// <summary>
        /// 测试连接
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<string> TempConnect([FromBody] OPCStartRequestModel model)
        {
            var svrMode = new OPCServerModel()
            {
                DAProgId = model.DAProgId.ToString(),
                AEProgId = model.AEProgId.ToString(),
                Id = model.Id,
                OPCServerIP = model.OPCServerIP,
            };
            return OpcDaServer.TempConnect(svrMode);
        }

        /// <summary>
        /// 根据Tag获取Station的名称
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<List<string>> GetTagsByStation([FromBody] TagRequestModel model)
        {
            var opcServer = OPCStartService._daServerList.Where(x => x._serverConfig.OPCServerIP == model.OPCIP).FirstOrDefault();
            if (opcServer != null)
            {
                return opcServer.GetTagsByStation(model.StationName).Select(o => o.Name).ToList();
            }
            else
            {
                SerilogServer.WriteLog("GetTagsByStation", new string[] { model.OPCIP + "OPC不存在" });
            }
            return new List<string>();
        }


        /// <summary>
        /// 开启服务
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<string> StartServer([FromBody] OPCStartRequestModel model)
        {
            try
            {
                var opcServer = OPCStartService._daServerList.Where(x => x._serverConfig.OPCServerIP == model.OPCServerIP).FirstOrDefault();
                if (opcServer == null)
                {
                    //int Id,string OPCServerIP, string DAProgId, string AEProgId, int SubsystemTypeId
                    OPCStartService.StartServer(model.Id, model.OPCServerIP, model.DAProgId, model.AEProgId, model.SubsystemTypeId);
                    return "OK";
                }
                else
                {
                    SerilogServer.WriteLog("StartServer", new string[] { model.OPCServerIP + "FreeOPC中已经开启" });
                    return "NOK";
                }
            }
            catch (Exception ex)
            {
                SerilogServer.WriteLog("StartServer", new string[] { model.OPCServerIP + ex.Message + ex.StackTrace });
                return "ERROR";
            }
        }

        /// <summary>
        /// 停止此服务 并移除OPC SERVER列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<string> StopServer([FromBody] OPCStartRequestModel model)
        {
            try
            {
                var opcServer = OPCStartService._daServerList.Where(x => x._serverConfig.OPCServerIP == model.OPCServerIP).FirstOrDefault();
                if (opcServer != null)
                {
                    OPCStartService.StopServer(model.OPCServerIP);
                    return "OK";
                }
                else
                {
                    SerilogServer.WriteLog("StopServer", new string[] { model.OPCServerIP + "FreeOPC中不存在此OPC" });
                    return "NOK";
                }
            }
            catch (Exception ex)
            {
                SerilogServer.WriteLog("StopServer", new string[] { model.OPCServerIP + ex.Message + ex.StackTrace });
                return "ERROR";
            }
        }
    }
}
